package o2o.service.code.impl;

import com.jinyou.utils.common.DateUtils;
import o2o.config.dao.UserDaoSql;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.code.TableCodeSequenceInfo;
import o2o.service.code.TableCodeSequenceService;
import org.springframework.stereotype.Service;

import java.sql.SQLException;

/**
 * Created with IntelliJ IDEA.
 *
 * @User: @Created by yangtk
 * @Date: @Date 2020/12/1 10:51
 * @Email: yangtongkuan@qq.com
 * @To change this template use File | Settings | File Templates.
 * @desc
 */
@Service
public class TableCodeSequenceServiceImpl implements TableCodeSequenceService {

    @Override
    public TableCodeSequenceInfo getOrCreateTableCodeSequenceByTypeAndKey(String type, String code) {
        StringBuilder sql = new StringBuilder();
        sql.append(" select * from ").append(PojoTables.TABLE_CODE_SEQUENCE)
                .append(" where delFlag = 0 and  type = '").append(type).append("' and code = '").append(code).append("' ");

        TableCodeSequenceInfo tableCodeSequenceInfo = null;
        try {
            tableCodeSequenceInfo = (TableCodeSequenceInfo) UserDaoSql.getInstance().getObject(TableCodeSequenceInfo.class, sql.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        if (tableCodeSequenceInfo == null) {
            tableCodeSequenceInfo = new TableCodeSequenceInfo();
            tableCodeSequenceInfo.setCode(code).setType(type).setCreateTime(DateUtils.getCurrTime()).setDelFlag(0).setfVersion(0).setSequence(0);
            try {
                UserDaoSql.getInstance().insertObj(PojoTables.TABLE_CODE_SEQUENCE, tableCodeSequenceInfo);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
                return null;
            }
            try {
                tableCodeSequenceInfo = (TableCodeSequenceInfo) UserDaoSql.getInstance().getObject(TableCodeSequenceInfo.class, sql.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
            return tableCodeSequenceInfo;
        } else {
            return tableCodeSequenceInfo;
        }
    }

    // 更新
    @Override
    public boolean updateTableSequenceByKey(String type, String code, Integer version, Integer sequence) {
        StringBuilder sql = new StringBuilder();
        sql.append(" update ").append(PojoTables.TABLE_CODE_SEQUENCE).append(" set fVersion = fVersion +1")
                .append(",sequence = ").append(sequence).append(" where delFlag= 0 and type = '").append(type)
                .append("'  and code ='").append(code).append("' and fversion =").append(version);
        try {
            int updateCount = UserDaoSql.getInstance().executeUpdateBySql(sql.toString());
            return updateCount > 0;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return false;
        }
    }
}
